package com.itheima.job;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.mongo.RecommendVideo;
import com.itheima.domain.mongo.Video;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
public class RecommendVideoJob {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Scheduled(cron = "0/30 * * * * ?")
    public void redisToMongo(){
        System.out.println("开启推荐视频同步...");
        //获取redis中的视频的keySey
        Set<String> ketSet = stringRedisTemplate.keys("VIDEOS_RECOMMEND_*");

        //判断是否为空
        if (CollectionUtil.isNotEmpty(ketSet)) {
            //遍历keySet
            for (String key : ketSet) {

                //获取用户id
                String userId = key.replace("VIDEOS_RECOMMEND_", "");

                //获取对应的推荐视频
                String vids = stringRedisTemplate.opsForValue().get(key);

                //删除之前推荐的视频
                mongoTemplate.remove(new Query(Criteria.where("userId").is(Long.valueOf(userId))), RecommendVideo.class);

                //遍历vids
                String[] vidList = vids.split(",");

                for (String vid : vidList) {
                    //根据vid查找视频,并封装recommendVideo
                    RecommendVideo recommendVideo = new RecommendVideo();
                    Video video = mongoTemplate.findOne(new Query(Criteria.where("vid").is(Long.valueOf(vid))), Video.class);
                    recommendVideo.setScore(RandomUtil.randomDouble(70,99));
                    recommendVideo.setDate(System.currentTimeMillis());
                    recommendVideo.setVid(Long.valueOf(vid));
                    recommendVideo.setVideoId(video.getId());
                    recommendVideo.setUserId(Long.valueOf(userId));

                    //插入推荐视频列表
                    mongoTemplate.save(recommendVideo);
                }


            }
        }
        System.out.println("推荐视频同步结束...");
    }
}
